package com.weiyuwqj.controller.user;

import com.weiyuwqj.api.model.BasUserInfo;
import com.weiyuwqj.api.service.BasTicketService;
import com.weiyuwqj.api.service.SysTempcodeService;
import com.weiyuwqj.api.service.BasUserService;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.BasTicket;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.SysTempcode;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.MD5;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;


/**
 * Created by zhangyong on 2016/11/23.
 * 注册
 */
@Controller
@RequestMapping("/register")
public class UserRegisterController{

    @Autowired
    BasUserService userService;
    @Autowired
    SysTempcodeService tempcodeService;
    @Autowired
    BasTicketService ticketService;

    @RequestMapping(value = "")
    public Object register(){
        return "main/register";
    }


    @RequestMapping(value = "/personRegister")
    public Object personRegister(){
        return Message.OK;
    }
    /**
     * 微信注册
     *
     * @param request
     * @param mobile      手机号码
     * @param pictureCode 图片验证码
     * @param mobileCode  手机验证码
     * @return
     */
    @ResponseBody
    @RequestMapping("/weixinRegister")
    public Object weixinRegister(HttpServletRequest request, String mobile, String pictureCode, String mobileCode,String invite,String source) {
        Object obj = request.getSession().getAttribute("validPhoneCode");
        Object timeObj =request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode="";
        if(obj ==null || timeObj==null){
            throw new CrowdException("auto.sms_not_exists");
        }
        Long validPhoneExpiredTime = (Long) timeObj;
        validPhoneCode=obj.toString();
        String verifyCode = request.getSession().getAttribute("verifyCode").toString();

        BasUser user=userService.getUserByMobile(mobile);
        if(user!=null){
            throw new CrowdException("sys.user.add.user_exist");
        }

        //校验图片验证码
        if(!verifyCode.equals(pictureCode)) {
            throw new CrowdException("picture_code_error");
        }


        //发送短信
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;

        if (!(validPhoneCode.equals(mobileCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }

        SysTempcode tempcode=tempcodeService.getByMobileAndCode(mobile, validPhoneCode);
        if(tempcode==null){
            throw new CrowdException("user.register.randomCode.error");
        }

        String salt = RandomCodesUtils.createRandom(false, 4);

        if(StringUtils.isNull(invite)){
            invite = "";
        }
        user=new BasUser();
        user.setAddtime(now);
        user.setAddip(IpUtils.get());
        user.setType(1);
        user.setStatus(1);
        if(!StringUtils.isNull(source)){
            user.setReferer("H5-"+source);
        }else {
            user.setReferer("H5");
        }
        user.setSalt(salt);
        try {
            user.setPassword(MD5.toMD5(mobile.substring(mobile.length()-6)+salt));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        user.setMobile(mobile);
        BasUserInfo info=new BasUserInfo();
        //info.setIsSecurityLimit(0);
        userService.doRegister(user, invite, info);
        request.getSession().removeAttribute("validPhoneExpiredTime");
        request.getSession().removeAttribute("validPhoneCode");
        return Message.OK;
    }

    /**
     * pc注册
     * @param request
     * @param mobile  手机号码
     * @param mobileCode  手机验证码
     * @param password  密码
     * @return
     */
    @ResponseBody
    @RequestMapping("/pcRegister")
    public Object pcRegister(HttpServletRequest request, String mobile, String mobileCode,String password,String invite,String source) {
/*
        Object obj = request.getSession().getAttribute("validPhoneCode");
        Object timeObj =request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode="";
        if(obj ==null || timeObj==null){
            throw new CrowdException("auto.sms_not_exists");
        }
        Long validPhoneExpiredTime = (Long) timeObj;
        validPhoneCode=obj.toString();
        //发送短信
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;


        if (!(validPhoneCode.equals(mobileCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }

        SysTempcode tempcode = tempcodeService.getByMobileAndCode(mobile, validPhoneCode);
        if (tempcode == null) {
            throw new CrowdException("user.register.randomCode.error");
        }
        */ //commented by Sam.Yi for testing

        String salt = RandomCodesUtils.createRandom(false, 4);

        BasUser user = new BasUser();
        user.setAddtime(new Date());
        user.setAddip(IpUtils.get());
        user.setType(1);
        user.setStatus(1);
        if(!StringUtils.isNull(source)){
            user.setReferer("PC-"+source);
        }else {
            user.setReferer("PC");
        }
        user.setSalt(salt);
        user.setMobile(mobile);
        user.setPassword(password);
        BasUserInfo info=new BasUserInfo();
        //info.setIsSecurityLimit(0);
        userService.doRegister(user, invite, info);
        request.getSession().removeAttribute("validPhoneExpiredTime");
        request.getSession().removeAttribute("validPhoneCode");
        return Message.OK;
    }


    /**
     * 转盘注册
     * @param request
     * @param mobile  手机号码
     * @param mobileCode  手机验证码
     * @return
     */
    @ResponseBody
    @RequestMapping("/lotteryRegister")
    public Object lotteryRegister(HttpServletRequest request, String mobile, String mobileCode) {

        Boolean b = DateUtils.getDateRange("2016-12-10 00:00:00", "2016-12-24 00:00:00");

        if(!b){
            throw new CrowdException("activity.timeout");
        }

        Object obj = request.getSession().getAttribute("validPhoneCode");
        Object timeObj =request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode="";
        if(obj ==null || timeObj==null){
            throw new CrowdException("auto.sms_not_exists");
        }
        Long validPhoneExpiredTime = (Long) timeObj;
        validPhoneCode=obj.toString();
//        Long validPhoneExpiredTime = Long.parseLong(request.getSession().getAttribute("validPhoneExpiredTime").toString());
//        String validPhoneCode = request.getSession().getAttribute("validPhoneCode").toString();
        //发送短信
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;

        if (!(validPhoneCode.equals(mobileCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }

        SysTempcode tempcode = tempcodeService.getByMobileAndCode(mobile, validPhoneCode);
        if (tempcode == null) {
            throw new CrowdException("user.register.randomCode.error");
        }

        String salt = RandomCodesUtils.createRandom(false, 4);

        String invite = "";



        BasUser user = userService.getUserByMobile(mobile);
        if(null != user){
            throw new CrowdException("lottery.user.already.exists");
        }
        user=new BasUser();
        user.setAddtime(now);
        user.setAddip(IpUtils.get());
        user.setType(1);
        user.setStatus(1);
        user.setReferer("PC");
        user.setSalt(salt);
        user.setMobile(mobile);
        BasUserInfo info=new BasUserInfo();
        //info.setIsSecurityLimit(0);
        Integer userId=userService.doRegister(user, invite, info);

        BasTicket ticket=new BasTicket();
        ticket.setUserId(userId);
        ticket.setAddip(IpUtils.get());
        ticket.setAddtime(new Date());
        ticket.setWay("上线抽奖");
        ticket.setRate(new BigDecimal(0.5));
        ticket.setExpiredTime(DateUtils.setDayLast(DateUtils.addDays(new Date(), Constants.days)));
        ticket.setRequireAmount(new BigDecimal(100));
        ticket.setUsefulLife(7);
        ticket.setStatus(2);
        ticket.setScope(30);
        ticketService.save(ticket);
        request.getSession().removeAttribute("validPhoneExpiredTime");
        request.getSession().removeAttribute("validPhoneCode");
        return Message.OK;
    }



}
